from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response

from django.db.models import F, Count
from yaml import serialize

from .models import Equipment
from .serializers import EquipmentOverviewSerializer, EquipmentSerializer, StateAnalyzeSerializer, DepartmentAnalyzeSerializer
from .pagination import CustomPagination


class EquipmentViewSet(viewsets.ModelViewSet):
    '''
    list: 查询所有Equipment
    create: 新增Equipment
    retrieve: 查询单个Equipment, 文档名: read,接口名: retrieve
    update: 更新Equipment
    destroy: 删除Equipment
    '''
    queryset = Equipment.objects.all()
    serializer_class = EquipmentSerializer
    pagination_class = CustomPagination

    @action(detail=False, methods=['get'])
    def equipment_overview(self, request):
        queryset = Equipment.objects.all().select_related(
            "department__leader",
            "category").annotate(leader_name=F('department__leader__username'),
                                 category_name=F('category__name'),
                                 department_name=F('department__name'))
        paginated_queryset = self.paginator.paginate_queryset(queryset,
                                                              request=request,
                                                              view=self)
        serializer = EquipmentOverviewSerializer(paginated_queryset, many=True)
        return self.paginator.get_paginated_response(serializer.data)

    @action(detail=False, methods=['put'])
    def update_equipment_batch(self, request):
        update_fields = request.data.get('editForm', {})
        update_fields = {k: v for k, v in update_fields.items() if v}
        ids = request.data['equipmentIdSelection']
        print('update_equipment_batch ', (update_fields), ids)
        if not update_fields:
            return Response({"error": "No fields to update"},
                            status=status.HTTP_400_BAD_REQUEST)

        queryset = Equipment.objects.filter(id__in=ids)
        queryset.update(**update_fields)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(detail=False, methods=['delete'])
    def delete_equipment_batch(self, request):
        ids = request.data['equipmentIdSelection']
        print('delete_equipment_batch ', ids)
        queryset = Equipment.objects.filter(id__in=ids)
        queryset.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(detail=False, methods=['get'])
    def category_state_count(self, request):
        queryset = Equipment.objects.all().select_related('category').values(
            'category__name', 'state').annotate(count=Count('id'))
        serializer = StateAnalyzeSerializer(queryset, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def department_count(self, request):
        queryset = Equipment.objects.all().values('department__name').annotate(
            count=Count('id'))
        serializer = DepartmentAnalyzeSerializer(queryset, many=True)
        return Response(serializer.data)
